package indi.jp.project.core.filter;

import indi.jp.project.core.util.JwtUtil;
import indi.jp.project.core.web.HttpRequestWrapper;
import io.jsonwebtoken.Claims;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
//        System.out.println("| -------------------- RequestFilter -------------------- |");
        String token = request.getHeader(JwtUtil.HEADER);
        // 如果有token就解析token内容放到parameter中供接口获取
        if (token != null && token.startsWith(JwtUtil.HEADER_PREFIX)) {
            HttpRequestWrapper wrapper = new HttpRequestWrapper(request);
            Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap());
            token = token.replace(JwtUtil.HEADER_PREFIX, "");
            Claims claims = JwtUtil.getTokenBody(token);
            String username = claims.getSubject();
            parameterMap.put("account", new String[]{username});
            wrapper.setParameterMap(parameterMap);
            super.doFilter(wrapper, response, chain);
        } else {
            super.doFilter(request, response, chain);
        }
    }
}
